/**
 * Copyright (c) 2018-2099, Chill Zhuang 庄骞 (bladejava@qq.com).
 * <p>
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl.html
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springblade.modules.restaurant.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.restaurant.entity.ExpensesCost;
import org.springblade.modules.restaurant.excel.ExpensesCostExcel;
import org.springblade.modules.restaurant.service.IExpensesCostService;
import org.springblade.modules.restaurant.vo.ExpensesCostVO;
import org.springframework.web.bind.annotation.*;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 费用支出记录表 控制器
 *
 * @author Blade
 * @since 2025-03-03
 */
@RestController
@AllArgsConstructor
@RequestMapping("/restaurant/expensescost")
@Tag(name = "费用支出记录表", description = "费用支出记录表接口")
public class ExpensesCostController extends BladeController {

	private IExpensesCostService expensesCostService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@Operation(summary = "详情", description = "传入expensesCost")
	public R<ExpensesCost> detail(ExpensesCost expensesCost) {
		ExpensesCost detail = expensesCostService.getOne(Condition.getQueryWrapper(expensesCost));
		return R.data(detail);
	}

	/**
	 * 分页 费用支出记录表
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@Operation(summary = "分页", description = "传入expensesCost")
	public R<IPage<ExpensesCost>> list(ExpensesCostVO expensesCost, Query query) {
		IPage<ExpensesCost> pages = expensesCostService.page(Condition.getPage(query), customizeQueryWrapper(expensesCost));
		return R.data(pages);
	}

	/**
	 * 自定义分页 费用支出记录表
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@Operation(summary = "分页", description = "传入expensesCost")
	public R<IPage<ExpensesCostVO>> page(ExpensesCostVO expensesCost, Query query) {
		IPage<ExpensesCostVO> pages = expensesCostService.selectExpensesCostPage(Condition.getPage(query), expensesCost);
		return R.data(pages);
	}

	/**
	 * 新增 费用支出记录表
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@Operation(summary = "新增", description = "传入expensesCost")
	public R save(@Valid @RequestBody ExpensesCost expensesCost) {
		return R.status(expensesCostService.save(expensesCost));
	}

	/**
	 * 修改 费用支出记录表
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@Operation(summary = "修改", description = "传入expensesCost")
	public R update(@Valid @RequestBody ExpensesCost expensesCost) {
		return R.status(expensesCostService.updateById(expensesCost));
	}

	/**
	 * 新增或修改 费用支出记录表
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@Operation(summary = "新增或修改", description = "传入expensesCost")
	public R submit(@Valid @RequestBody ExpensesCost expensesCost) {
		return R.status(expensesCostService.saveOrUpdate(expensesCost));
	}


	/**
	 * 删除 费用支出记录表
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@Operation(summary = "逻辑删除", description = "传入ids")
	public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String ids) {
		return R.status(expensesCostService.deleteLogic(Func.toLongList(ids)));
	}


	@SneakyThrows
	@GetMapping("/export")
	@ApiOperationSupport(order = 8)
	@Operation(summary = "导出", description = "传入ids")
	public void export(ExpensesCostVO cost, HttpServletResponse response) {
		List<ExpensesCost> list = expensesCostService.list(customizeQueryWrapper(cost));
		List<ExpensesCostExcel> excels = BeanUtil.copyToList(list, ExpensesCostExcel.class);

		response.setContentType("application/vnd.ms-excel");
		response.setCharacterEncoding(StandardCharsets.UTF_8.name());
		String fileName = URLEncoder.encode("费用支出", StandardCharsets.UTF_8)
			+ "_" + DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_PATTERN);

		response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
		EasyExcel.write(response.getOutputStream(), ExpensesCostExcel.class).sheet("费用支出").doWrite(excels);
	}
	private Wrapper<ExpensesCost> customizeQueryWrapper(ExpensesCostVO expensesCost) {

		String[] searchTime = expensesCost.getSearchTime();
		DateTime now = DateUtil.date();

		// 获取当前时间
		String endTime = DateUtil.formatDate(now);
		// 获取当月开始时间
		String startTime = DateUtil.formatDate(DateUtil.beginOfMonth(now));

		if (searchTime != null && searchTime.length == 2) {
			startTime = searchTime[0];
			endTime = searchTime[1];
		}

		return Wrappers.<ExpensesCost>lambdaQuery()
			.between(ExpensesCost::getTime, startTime, endTime)
			.like(StrUtil.isNotBlank(expensesCost.getName()), ExpensesCost::getName, expensesCost.getName())
			.eq(ObjectUtil.isNotNull(expensesCost.getIsAvg()), ExpensesCost::getIsAvg, expensesCost.getIsAvg())
			.orderByDesc(ExpensesCost::getTime);
	}
}
